<template>
	<div v-loading="data.mtloading">

		<div class="app-container">

			<el-form :model="data.info" :rules="data.rules" class="w-full mt-4"
				:label-width="language == 'en' ? '150' : '120'" ref="ruleFormRef">

				<el-form-item :label="$t('goods.corner.name') + ':'" prop="corner_name" class="w-1/2">
					<el-input v-model="data.info.corner_name" :placeholder="$t('message.pleaseEnter')" />
				</el-form-item>

				<el-form-item :label="$t('goods.corner.timeType') + ':'" prop="timetype" class="w-1/2">
					<el-select v-model="data.timetype" :placeholder="$t('message.pleaseSelect')">
						<el-option :label="$t('goods.corner.timeLimit')" :value="1" />
						<el-option :label="$t('goods.corner.indefinite')" :value="2" />
					</el-select>
				</el-form-item>

				<el-form-item v-if="data.timetype == 1" :label="$t('date.applyTime') + ':'" prop="dtime" class="w-1/2">
					<el-date-picker v-model="data.info.dtime" :disabled-date="disabledDate" type="daterange"
						:range-separator="$t('public.to')" :start-placeholder="$t('date.startTimes')"
						:end-placeholder="$t('date.endTimes')" format="YYYY/MM/DD" value-format="x"
						:shortcuts="shortcuts" />
				</el-form-item>

				<el-form-item v-if="data.timetype == 2" :label="$t('date.applyTime') + ':'" prop="time" class="w-1/2">
					<el-date-picker v-model="data.info.time" :disabled-date="disabledDate" type="date"
						format="YYYY/MM/DD" value-format="x" style="width: 100%;"
						:placeholder="$t('message.pleaseSelect')" />
				</el-form-item>

				<el-form-item :label="$t('goods.corner.type') + ':'" prop="corner_type" class="w-1/2">
					<el-select v-model="data.info.corner_type" :placeholder="$t('message.pleaseSelect')"
						@change="getcornertype">
						<el-option :label="$t('goods.corner.new')" :value="1" />
						<el-option :label="$t('goods.corner.explosive')" :value="2" />
						<el-option :label="$t('goods.corner.hot')" :value="3" />
						<el-option :label="$t('goods.corner.customize')" :value="4" />
					</el-select>
				</el-form-item>

				<el-form-item v-if="data.info.corner_type == 4" :label="$t('goods.corner.upload') + ':'" prop="pic"
					class="w-1/2">
					<el-input v-model="data.info.pic" readonly :placeholder="$t('goods.corner.pleaseUpload')">
						<template #append>
							<Upload :list="{ 'data': 'subscript_img', 'list': false }" :type="1" :uptype="2"
								@exposeData="expose" />
						</template>
					</el-input>
				</el-form-item>

				<el-form-item v-if="data.info.corner_type != 4" :label="$t('goods.corner.style') + ':'" prop="style"
					class="w-1/2">
					<el-select v-model="data.info.style" :placeholder="$t('message.pleaseSelect')"
						@change="getcornertype">
						<el-option :label="$t('goods.corner.circle')" :value="1" />
						<el-option :label="$t('goods.corner.triangle')" :value="2" />
						<el-option :label="$t('goods.corner.shaped')" :value="3" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('goods.corner.position') + ':'" prop="position" class="w-1/2">
					<el-select v-model="data.info.position" :placeholder="$t('message.pleaseSelect')"
						@change="getcornertype">
						<el-option :label="$t('goods.corner.left')" :value="1" />
						<el-option :label="$t('goods.corner.right')" :value="2" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('goods.corner.subscript') + ':'" class="w-1/2">
					<div class="w-80 h-80 relative">
						<el-image :src="imagesMap['corner_bg']" style="height:100%;width: 100%;" />
						<div :class="'w-full absolute top-0 ' + [data.info.position == 1 ? 'text-left' : 'text-right']">
							<el-image :src="data.imgurl" style="height:80px;width: 80px;" />
						</div>
					</div>
				</el-form-item>

				<el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="machineList" class="w-1/2"
					v-prmis="'machine_group_mg_getList'">

					<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)" @visible-change="onVisibleChange"/>

					<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
						style="width:40%;" @change="getmping($event, 2)">
						<el-option v-for="item in data.maclist" :key="item.m_id"
							:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
					</el-select>

					<div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
						<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
							class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
							@close="handleClose(key)">
							{{ item.machine_id || '' }}{{ item.mg_name || item.label ||' - ' + item.machine_name }}
						</el-tag>
					</div>

				</el-form-item>

				<el-form-item :label="$t('goods.corner.applica') + ':'" prop="goodsList" class="w-1/2">
					<el-select v-model="data.info.goodsList" :placeholder="$t('message.pleaseSelect')" clearable
						filterable multiple @change="godoption">
						<template #header>
							<el-checkbox v-model="data.godcheckAll" :indeterminate="data.godindeterminate"
								@change="godsCheckAll">{{ $t('public.selectAll') }}</el-checkbox>
						</template>
						<el-option v-for="item in data.godlist" :key="item.m_id"
							:label="item.g_id + ' - ' + item.g_name" :value="item.g_id" />
					</el-select>
				</el-form-item>

				<div class="w-1/2 text-center mt-4 ml-6">
					<div class="inline-block">

						<el-button type="primary" size="small" @click="submit(ruleFormRef)"
							v-prmis="'machine_group_mg_getList'">
							<template #default>
								<span class="text-sm">{{ $t('public.save') }}</span>
							</template>
						</el-button>

						<el-button size="small" @click="cancell">
							<template #default>
								<span class="text-sm">{{ $t('public.cancel') }}</span>
							</template>
						</el-button>
					</div>
				</div>
			</el-form>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import Upload from '@/components/Upload/index.vue';
import imagesMap from '@/assets/images_Js.ts';
import { getmachineList } from '@/api/machine';
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getgoodsList, addcornerList } from '@/api/goods';
import { useRouter } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
let ruleFormRef = ref<any>();
const router = useRouter()

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue:[],
	nodesData:[],
	mtloading: false, // 加载
	original: '', // 原始数据
	imgurl: imagesMap['left_new_circular'], // 角标图片
	timetype: 1, // 1日期范围、2无限期
	// maccheckAll:false, // 全选设备
	// macindeterminate:false, // 设备部分选中
	godcheckAll: false, // 商品全选
	godindeterminate: false, // 商品部分选中
	maclist: [], // 设备列表
	godlist: [], // 商品列表

	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备

	info: { // 主体信息
		corner_name: '',
		corner_type: 1,
		pic: '',
		style: 1,
		position: 1,
		time: '',
		dtime: [],
		goodsList: [],
		machineList: [],
	},
	rules: { // 表单验证
		corner_name: { required: true, message: $t('message.pleaseEnter'), trigger: 'blur' },
		time: { required: true, message: $t('message.pleaseSelect'), trigger: 'blur' },
		dtime: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
		goodsList: { required: true, message: $t('message.pleaseSelect'), trigger: 'change' },
	},
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 获取接口信息
let geturlinfo = async () => {
	data.original = JSON.stringify(data.info)

	// 获取设备信息
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})
	// 获取商品信息
	await getgoodsList().then(res => {
		if (res.state == 200) {
			data.godlist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})
}

// 选择角标类型
let getcornertype = () => {

	if (data.info.corner_type == 4) {
		data.imgurl = data.info.pic
		return
	}

	// 左上角、右上角 position
	let iposition = ['left_', 'right_']

	// 品类 新品、爆品、热销 corner_type
	let icategory = ['new_', 'burst_', 'heat_']

	// 形态 圆形、三角、Q形 style
	let iform = ['circular', 'triangle', 'q']

	let url = iposition[data.info.position - 1] + icategory[data.info.corner_type - 1] + iform[data.info.style - 1]

	data.imgurl = imagesMap[url]
}

// 上传返回
let expose = (e) => {
	if (e.status == 200) {
		data.info.pic = e.file.response.data
		data.imgurl = e.file.response.data
	} else {
		data.info.pic = ''
		data.imgurl = ''
	}
}

// // 选中设备
// let onoption = () => {
// 	if (data.info.machineList.length == 0) {
// 		data.maccheckAll = false;
// 		data.macindeterminate = false;
// 	} else {
// 		if (data.info.machineList.length == data.maclist.length) {
// 			data.maccheckAll = true;
// 			data.macindeterminate = false;
// 		} else {
// 			data.maccheckAll = false;
// 			data.macindeterminate = true;
// 		}
// 	}
// }

// 设备全选
// let handleCheckAll = (val) => {
// 	if (val) {
// 		data.info.machineList = data.maclist.map(_ => _.machine_id);
// 		data.maccheckAll = true
// 		data.macindeterminate = false
// 	} else {
// 		data.info.machineList = [];
// 	}
// }

// 选中商品
let godoption = () => {
	if (data.info.goodsList.length == 0) {
		data.godcheckAll = false;
		data.godindeterminate = false;
	} else {
		if (data.info.goodsList.length == data.godlist.length) {
			data.godcheckAll = true;
			data.godindeterminate = false;
		} else {
			data.godcheckAll = false;
			data.godindeterminate = true;
		}
	}
}

// 商品全选
let godsCheckAll = (val) => {
	if (val) {
		data.info.goodsList = data.godlist.map(_ => _.g_id);
		data.godcheckAll = true
		data.godindeterminate = false
	} else {
		data.info.goodsList = [];
	}
}
let onVisibleChange = () =>{
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}
}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid, fields) => {
		if (valid) {

			let obj = {}
			let machine = []
			for (let key in data.info) {
				if (key != 'time' && key != 'dtime') {
					obj[key] = data.info[key]
				}
			}

			obj.start_time = Math.floor(data.info.time / 1000)
			obj.end_time = ''
			if (data.timetype == 1) {
				obj.start_time = Math.floor(data.info.dtime[0] / 1000)
				obj.end_time = Math.floor(data.info.dtime[1] / 1000)
			}
			obj.goodsList = obj.goodsList.join(',')

			if (obj.corner_type == 4 && obj.pic == '') {
				ElMessage({
					message: $t('message.pleaseUpCornerMark'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length == 0) {
				ElMessage({
					message: $t('message.pleaseSelectMachine'),
					type: 'error'
				})
				return
			}

			if (data.grouping.length != 0) {
				let grouping = []
				for (let item of data.grouping) {
					// 设备
					if (item.mg_id != undefined) {
						data.bindmacping.map((ime) => {
							if (item.mg_id === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}

					if (item.machine_id != undefined) {
						grouping.push(item.machine_id)
					}
					// 设备分组
					if (item.value != undefined) {
						data.bindmacping.map((ime) => {
							if (item.value === ime.mg_id) {
								grouping.push(ime.machine_id)
							}
						})
					}
				}
				// 设备分组放入指定设备中
				machine = [...machine, ...grouping]
			}

			// 去除重复的设备编号
			machine = [...new Set(machine)]

			obj.machineList = machine.join(',')

			addcornerList(obj).then(res => {
				data.mtloading = false
				if (res.state == 200) {
					ElMessage({
						message: $t('message.addSuccess'),
						type: 'success'
					})
					router.back()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})

		}
	})
}

// 取消
let cancell = () => {
	data.godcheckAll = false
	data.godindeterminate = false
	data.timetype = 1
	data.info = JSON.parse(data.original)
	getcornertype()
	router.back()
}

geturlinfo()

</script>
